package com.example.service;

import com.example.entity.Vehicle;
import com.example.entity.VehicleStatus;
import com.example.entity.OrderType;
import com.example.entity.VehicleType;
import com.example.repository.VehicleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class VehicleService {
    private final VehicleRepository vehicleRepository;

    @Autowired
    public VehicleService(VehicleRepository vehicleRepository) {
        this.vehicleRepository = vehicleRepository;
    }

    @Cacheable(value = "vehicles", key = "#status.name()")
    public List<Vehicle> findByStatus(VehicleStatus status) {
        return vehicleRepository.findByStatus(status);
    }

    public List<Vehicle> getAvailableVehicles(OrderType type) {
        List<Vehicle> availableVehicles = findByStatus(VehicleStatus.AVAILABLE);
        // 根据订单类型过滤车辆
        return availableVehicles.stream()
                .filter(v -> matchesVehicleType(v, type))
                .collect(Collectors.toList());
    }

    private boolean matchesVehicleType(Vehicle vehicle, OrderType type) {
        switch (type) {
            case ECONOMY:
                return vehicle.getType() == VehicleType.ECONOMY;
            case LUXURY:
                return vehicle.getType() == VehicleType.LUXURY;
            case CARPOOL:
                return vehicle.isCanCarpool();
            case AUTONOMOUS:
                return vehicle.isAutonomous();
            default:
                return false;
        }
    }

    public void markVehicleInService(Vehicle vehicle) {
        vehicle.setStatus(VehicleStatus.ON_TRIP);
        vehicleRepository.save(vehicle);
    }

    public void markVehicleAvailable(Vehicle vehicle) {
        vehicle.setStatus(VehicleStatus.AVAILABLE);
        vehicleRepository.save(vehicle);
    }
}